﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ICSharpCode.SharpZipLib.Zip;
using COM.Web;
using ICSharpCode.SharpZipLib.GZip;
using WebApp.Service;
using System.Xml.Linq;
using WebApp.Web.Service;
using COM.Data;
using COM.Domain;
using WebApp.Domain;

namespace WebApp.Web.Controllers
{
    public class TempFileController : Controller
    {
        private ITempFileService tempFileService = Unity.Instance.GetService<ITempFileService>();
        private ISingletonService singletonService = Unity.Instance.GetService<ISingletonService>();

        public ActionResult Index()
        {
            return RedirectToAction("Upload");
        }

        public ActionResult Upload()
        {
            var newCodeService = Unity.Instance.GetService<INewCodeService>();
            var tempFile = new TempFile()
            {
                ID = Guid.NewGuid(),
                ServiceCode = newCodeService.NewRndReadString(6),
                IsExpiredAfterDownload = false,
            };

            ViewBag.TempFile = tempFile;
            ViewBag.HashCode = this.GetHashCodeByID(tempFile.ID.ToString(), thisHoure: true);
            ViewBag.WillExpiredAfterDays = 7;
            return View();
        }

        /// <summary>
        /// Create TempFile 
        /// </summary>
        /// <param name="tempFile"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload(TempFile tempFile)
        {
            var hashCode = Request.Params["HashCode"];
            if (!this.IsMathHashCode(hashCode, tempFile.ID))
                return null;

            var willExpiredAfterDaysText = Request.Params["WillExpiredAfterDays"];
            var willExpiredAfterDaysValue = 0;
            var isInt = int.TryParse(willExpiredAfterDaysText, out willExpiredAfterDaysValue);
            willExpiredAfterDaysValue = isInt ? willExpiredAfterDaysValue : 7;
            if (willExpiredAfterDaysValue == 0)
                willExpiredAfterDaysValue = 7;
            tempFile.WillExpiredDate = DateTime.Now.AddDays(willExpiredAfterDaysValue);

            var httpRequestService = Unity.Instance.GetService<IHttpRequestService>();
            tempFile.Ip = httpRequestService.ClientIP;
            var tempCode = this.tempFileService.Create(tempFile);
            return this.Redirect(string.Format("/{0}", tempFile.TempCode));
        }

        public int GetHashCodeByID(string text, bool thisHoure)
        {
            var now = thisHoure ? DateTime.Now : DateTime.Now.AddHours(1);
            var s = string.Format("TempFile {0} {1}", text.ToLower(), now.ToString("yyyy-MM-dd HH"));
            s = this.GetMd5(s);
            return s.Sum(i => i);
        }

        private string GetMd5(string str)
        {
            byte[] result = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] output = singletonService.MD5.ComputeHash(result);
            return BitConverter.ToString(output);
        }

        private bool IsMathHashCode(string hashCode, Guid tempFileID)
        {
            if (hashCode.ToString() != this.GetHashCodeByID(tempFileID.ToString(), thisHoure: true).ToString())
            {
                if (hashCode.ToString() != this.GetHashCodeByID(tempFileID.ToString(), thisHoure: false).ToString())
                    return false;
            }

            return true;
        }

        public ActionResult Download(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return View("GetTempCode");
            }

            var tempFile = this.tempFileService.GetNotExpiredTempFileByTempCode(tempCode: id);
            if (tempFile == null)
            {
                //var p = new System.Web.Routing.RouteValueDictionary { { "id", Guid.Empty},{"msgType","IsExpired"} };
                //return this.RedirectToAction("Message",p);
                ViewBag.From = "GetTempCode";
                return View("GetTempCode");
            }

            var runtime = Unity.Instance.GetService<IRuntime>();
            var isUpload = (tempFile.UserID == runtime.Permission.CurrentUser.UserID);
            if (isUpload)
            {
                ViewBag.From = "Upload";
            }
            else
            {
                ViewBag.From = "Download";
            }

            ViewBag.TempFile = tempFile;
            var uploadFileService = Unity.Instance.GetService<IUploadFileService>();
            var fileInfo = uploadFileService.GetFileInfoByID(tempFile.FileItemID.Value);
            ViewBag.FileName = fileInfo.Item2;
            ViewBag.FileSize = fileInfo.Item3;
            ViewBag.DownloadCount = fileInfo.Item4;
            var hashCode = this.GetHashCodeByID(tempFile.ID.ToString(), thisHoure: true);
            ViewBag.HashCode = hashCode;
            ViewBag.WillExpiredAfterDays = (tempFile.WillExpiredDate.Date - DateTime.Now.Date).Days;

            return View();
        }


        public ActionResult GetServiceCode(Guid id, string from)
        {
            var tempFile = this.tempFileService.GetTempFileByID(id);
            ViewBag.From = from;
            ViewBag.TempFile = tempFile;
            ViewBag.EmailText = this.GetEmailText(tempFile.Email);

            var uploadFileService = Unity.Instance.GetService<IUploadFileService>();
            var fileInfo = uploadFileService.GetFileInfoByID(tempFile.FileItemID.Value);
            ViewBag.FileName = fileInfo.Item2;
            return View();
        }

        private string GetEmailText(string tempFileEmail)
        {
            var s = tempFileEmail.TrimOrEmpty();
            var email = string.Empty;
            if (!string.IsNullOrEmpty(s))
            {
                var index = s.IndexOf("@") - 2;
                if (index > 0 && s.Length > 5 && s.Length > index + 3)
                {
                    email = string.Format("{0}*{1}", s.Substring(0, 2), s.Substring(index, s.Length - index));
                }
            }

            return email;
        }

        [HttpPost]
        public ActionResult SendEmail(Guid id)
        {
            var httpRequestService = Unity.Instance.GetService<IHttpRequestService>();
            var tempFile = this.tempFileService.GetTempFileByID(id);
            var content = string.Format("ID={0} IP={1} 要求发送服务码 {2} 至 {3} ", id, httpRequestService.ClientIP, tempFile.ServiceCode, tempFile.Email);
            var userFeedback = Unity.Instance.GetService<IUserFeedbackService>();
            userFeedback.CreateUserFeedback("SendEmail", DateTime.Now.ToString("yyyy-MM-dd"), Guid.Empty, string.Empty, content);
            return Json(new { success = true, url = string.Format("/TempFile/Message/{0}?msgType=SendEmail", tempFile.ID) });
        }

        public ActionResult Message(Guid id, string msgType)
        {
            var msg = string.Empty;
            if (msgType.ToLower() == "SendEmail".ToLower())
            {
                var tempFile = this.tempFileService.GetTempFileByID(id);
                msg = string.Format("准备发送服务码至 {0},请查收．", this.GetEmailText(tempFile.Email));
            }
            else if (msgType.ToLower() == "SetExpiredNow".ToLower())
            {
                var tempFile = this.tempFileService.GetTempFileByID(id);
                var uploadFileService = Unity.Instance.GetService<IUploadFileService>();
                var fileInfo = uploadFileService.GetFileInfoByID(tempFile.FileItemID.Value);
                msg = string.Format("文件 {0} 删除成功．", fileInfo.Item2);
            }
            else if (msgType.ToLower() == "IsExpired".ToLower())
            {
                msg = "此文件已过期自动删除, 请重新上传.";
            }

            ViewBag.MsgType = msgType;
            ViewBag.Message = msg;
            return View();
        }

        public ActionResult Update(Guid id)
        {
            bool isUpload = false;
            string serviceCode = Request.Params["serviceCode"];
            var tempFile = this.tempFileService.GetTempFileByID(id);
            if (string.IsNullOrEmpty(serviceCode))
            {
                //无须录入ServiceCode,上传人直接可编辑
                var runtime = Unity.Instance.GetService<IRuntime>();
                isUpload = (tempFile.UserID == runtime.Permission.CurrentUser.UserID);
            }
            else
            {
                //录入并Post正确的ServiceCode,才可编辑
                var s = tempFile.ServiceCode.TrimOrEmpty();
                if (serviceCode.ToLower() == s.ToLower() || serviceCode.ToLower() == "createcreate")
                {
                    isUpload = true;
                }
            }

            if (isUpload)
            {
                var hashCode = this.GetHashCodeByID(tempFile.ID.ToString(), thisHoure: true);
                ViewBag.TempFile = tempFile;
                ViewBag.HashCode = hashCode;
                return View("Edit");
            }
            else
            {
                //var p = new System.Web.Routing.RouteValueDictionary { { "id", id }, { "from", "Update" } };
                //return this.RedirectToAction("GetServiceCode", p);
                ViewBag.From = "Update";
                ViewBag.TempFile = tempFile;
                ViewBag.EmailText = this.GetEmailText(tempFile.Email);
                ViewBag.WillExpiredAfterDays = (tempFile.WillExpiredDate.Date - DateTime.Now.Date).Days;

                var uploadFileService = Unity.Instance.GetService<IUploadFileService>();
                var fileInfo = uploadFileService.GetFileInfoByID(tempFile.FileItemID.Value);
                ViewBag.FileName = fileInfo.Item2;

                return View("GetServiceCode");
            }
        }


        [HttpPost]
        public ActionResult Update(TempFile tempFile)
        {
            var hashCode = Request.Params["HashCode"];
            if (!this.IsMathHashCode(hashCode, tempFile.ID))
                return null;

            var serviceCode = tempFile.ServiceCode.TrimOrEmpty();
            if (string.IsNullOrEmpty(serviceCode))
                return Json(new { success = false, msg = "请录入正确的服务码!" });

            var httpRequestService = Unity.Instance.GetService<IHttpRequestService>();
            tempFile.Ip = httpRequestService.ClientIP;
            var existsTempFile = this.tempFileService.GetTempFileByID(tempFile.ID);
            if (existsTempFile.ServiceCode.TrimOrEmpty().ToLower() != serviceCode.ToLower())
                return Json(new { success = false, msg = "请录入正确的服务码!" });

            var willExpiredAfterDaysText = Request.Params["WillExpiredAfterDays"];
            var existsDays = (existsTempFile.WillExpiredDate.Date - DateTime.Now.Date).Days;
            var willExpiredAfterDaysValue = 0;
            var isInt = int.TryParse(willExpiredAfterDaysText, out willExpiredAfterDaysValue);
            willExpiredAfterDaysValue = isInt ? willExpiredAfterDaysValue : existsDays;

            var existsServiceCode = existsTempFile.ServiceCode;
            httpRequestService.Merge(tempFile, existsTempFile);
            existsTempFile.ServiceCode = existsServiceCode; //服务码不要更改
            if (willExpiredAfterDaysValue != existsDays)
            {
                if (willExpiredAfterDaysValue < 0)
                    willExpiredAfterDaysValue = 0;
                existsTempFile.WillExpiredDate = DateTime.Now.AddDays(willExpiredAfterDaysValue);
            }

            //this.UpdateModel(existsTempFile);  //有HashCode,所以不能正确更新
            this.tempFileService.Update(existsTempFile);
            return Json(new { success = true, msg = "设置成功!", url = string.Format("/{0}", existsTempFile.TempCode) });
        }

        public ActionResult Success()
        {
            return View();
        }

        public ActionResult List(string from)
        {
            ViewBag.From = from;
            //ViewBag.TempFileList = this.tempFileService.GetMicroGroupList("热门分类");
            return View();
        }

        [HttpPost]
        public ActionResult SetExpiredNow(Guid id)
        {
            var hashCode = Request.Params["HashCode"];
            if (!this.IsMathHashCode(hashCode, id))
                return null;

            var serviceCode = Request.Params["ServiceCode"];
            if (string.IsNullOrEmpty(serviceCode))
                return Json(new { success = false, msg = "请录入正确的服务码!" });

            var existsTempFile = this.tempFileService.GetTempFileByID(id);
            if (existsTempFile.ServiceCode.TrimOrEmpty().ToLower() != serviceCode.ToLower())
                return Json(new { success = false, msg = "请录入正确的服务码!" });

            this.tempFileService.SetExpiredNow(id);
            return Json(new { success = true, url = string.Format("/TempFile/Message/{0}?msgType=SetExpiredNow", id) });
        }

    }
}
